import store from '@store';
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { HttpStatus } from './http_status'

/**
 * 导出 Axios
 */
export class Axios {

    private api: AxiosInstance;

    public constructor (path: string) {
        this.api = axios.create({
            baseURL: `http://www.olah.com/api/${path}`,
            timeout: 5000,
            responseType: 'json'
        })
        this.initInterceptors()
    }

    /**
     * 响应拦截器
     */
    private initInterceptors() {
        this.api.interceptors.response.use(
            (response) => {
                let msg: string = response.data.msg;
                if (msg != undefined) {
                    if (response.data.status === HttpStatus.SUCCESS) {
                        msg.notifyOK()
                    } else {
                        msg.notifyWarn();
                    }
                }
                store.commit('refresh')
                return response.data
            },
            () => {
                '网络请求异常，请稍后再试'.notifyError();
            }
        )
    }
    
    public get<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> {
        return this.api.get(url, config);
    }

    public post<T, R = AxiosResponse<T>> (url: string, data?: any, config?: AxiosRequestConfig): Promise<R> {
        return this.api.post(url, data, config);
    }

}